﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.SessionState;
using System.Security;
using System.Security.AccessControl;
using System.Management;
using System.Management.Instrumentation;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Collections;
using System.Linq;

namespace MasterWebsite.Editor.aspnet
{
    public partial class Documents : System.Web.UI.Page
    {

        //system root path
        string strDriveLetter = ConfigurationManager.AppSettings["DirectFolder"].ToString();
        //website path
        string strDefaultPath = "documents";

        public static string Convert(string text)
        {
            //Ky tu dac biet

            // for (int i = 32; i < 48; i++)
            //{
            //     text = text.Replace(((char)i).ToString(), "-");
            //}
            //text = text.Replace(".", "-");
            text = text.Replace(" ", "");
            text = text.Replace(",", "");
            text = text.Replace(";", "");
            text = text.Replace(":", "");
            text = text.Replace("&", "");
            text = text.Replace("$", "");
            text = text.Replace("#", "");
            text = text.Replace("@", "");
            text = text.Replace("?", "");
            text = text.Replace("%", "");
            text = text.Replace("!", "");
            text = text.Replace("`", "");
            text = text.Replace("'", "");
            text = text.Replace("/", "");
            text = text.Replace("^", "");
            text = text.Replace("(", "");
            text = text.Replace(")", "");
            text = text.Replace("<", "");
            text = text.Replace(">", "");
            text = text.Replace("{", "");
            text = text.Replace("}", "");
            text = text.Replace("[", "");
            text = text.Replace("]", "");
            text = text.Replace("+", "");
            text = text.Replace("=", "");
            text = text.Replace("*", "");
            //'Dấu Ngang
            text = text.Replace("A", "A");
            text = text.Replace("a", "a");
            text = text.Replace("Ă", "A");
            text = text.Replace("ă", "a");
            text = text.Replace("Â", "A");
            text = text.Replace("â", "a");

            text = text.Replace("E", "E");
            text = text.Replace("e", "e");
            text = text.Replace("Ê", "E");
            text = text.Replace("ê", "e");
            text = text.Replace("I", "I");
            text = text.Replace("i", "i");
            text = text.Replace("O", "O");
            text = text.Replace("o", "o");
            text = text.Replace("Ô", "O");
            text = text.Replace("ô", "o");
            text = text.Replace("Ơ", "O");
            text = text.Replace("ơ", "o");
            text = text.Replace("U", "U");
            text = text.Replace("u", "u");
            text = text.Replace("Ư", "U");
            text = text.Replace("ư", "u");
            text = text.Replace("Y", "Y");
            text = text.Replace("y", "y");

            //    'Dấu Huyền
            text = text.Replace("À", "A");
            text = text.Replace("à", "a");
            text = text.Replace("Ằ", "A");
            text = text.Replace("ằ", "a");
            text = text.Replace("Ầ", "A");
            text = text.Replace("ầ", "a");
            text = text.Replace("È", "E");
            text = text.Replace("è", "e");
            text = text.Replace("Ề", "E");
            text = text.Replace("ề", "e");
            text = text.Replace("Ì", "I");
            text = text.Replace("ì", "i");
            text = text.Replace("Ò", "O");
            text = text.Replace("ò", "o");
            text = text.Replace("Ồ", "O");
            text = text.Replace("ồ", "o");
            text = text.Replace("Ờ", "O");
            text = text.Replace("ờ", "o");
            text = text.Replace("Ù", "U");
            text = text.Replace("ù", "u");
            text = text.Replace("Ừ", "U");
            text = text.Replace("ừ", "u");
            text = text.Replace("Ỳ", "Y");
            text = text.Replace("ỳ", "y");

            //'Dấu Sắc
            text = text.Replace("Á", "A");
            text = text.Replace("á", "a");
            text = text.Replace("Ắ", "A");
            text = text.Replace("ắ", "a");
            text = text.Replace("Ấ", "A");
            text = text.Replace("ấ", "a");
            text = text.Replace("É", "E");
            text = text.Replace("é", "e");
            text = text.Replace("Ế", "E");
            text = text.Replace("ế", "e");
            text = text.Replace("Í", "I");
            text = text.Replace("í", "i");
            text = text.Replace("Ó", "O");
            text = text.Replace("ó", "o");
            text = text.Replace("Ố", "O");
            text = text.Replace("ố", "o");
            text = text.Replace("Ớ", "O");
            text = text.Replace("ớ", "o");
            text = text.Replace("Ú", "U");
            text = text.Replace("ú", "u");
            text = text.Replace("Ứ", "U");
            text = text.Replace("ứ", "u");
            text = text.Replace("Ý", "Y");
            text = text.Replace("ý", "y");

            //'Dấu Hỏi
            text = text.Replace("Ả", "A");
            text = text.Replace("ả", "a");
            text = text.Replace("Ẳ", "A");
            text = text.Replace("ẳ", "a");
            text = text.Replace("Ẩ", "A");
            text = text.Replace("ẩ", "a");
            text = text.Replace("Ẻ", "E");
            text = text.Replace("ẻ", "e");
            text = text.Replace("Ể", "E");
            text = text.Replace("ể", "e");
            text = text.Replace("Ỉ", "I");
            text = text.Replace("ỉ", "i");
            text = text.Replace("Ỏ", "O");
            text = text.Replace("ỏ", "o");
            text = text.Replace("Ổ", "O");
            text = text.Replace("ổ", "o");
            text = text.Replace("Ở", "O");
            text = text.Replace("ở", "o");
            text = text.Replace("Ủ", "U");
            text = text.Replace("ủ", "u");
            text = text.Replace("Ử", "U");
            text = text.Replace("ử", "u");
            text = text.Replace("Ỷ", "Y");
            text = text.Replace("ỷ", "y");

            //'Dấu Ngã   
            text = text.Replace("Ã", "A");
            text = text.Replace("ã", "a");
            text = text.Replace("Ẵ", "A");
            text = text.Replace("ẵ", "a");
            text = text.Replace("Ẫ", "A");
            text = text.Replace("ẫ", "a");
            text = text.Replace("Ẽ", "E");
            text = text.Replace("ẽ", "e");
            text = text.Replace("Ễ", "E");
            text = text.Replace("ễ", "e");
            text = text.Replace("Ĩ", "I");
            text = text.Replace("ĩ", "i");
            text = text.Replace("Õ", "O");
            text = text.Replace("õ", "o");
            text = text.Replace("Ỗ", "O");
            text = text.Replace("ỗ", "o");
            text = text.Replace("Ỡ", "O");
            text = text.Replace("ỡ", "o");
            text = text.Replace("Ũ", "U");
            text = text.Replace("ũ", "u");
            text = text.Replace("Ữ", "U");
            text = text.Replace("ữ", "u");
            text = text.Replace("Ỹ", "Y");
            text = text.Replace("ỹ", "y");

            //'Dẫu Nặng
            text = text.Replace("Ạ", "A");
            text = text.Replace("ạ", "a");
            text = text.Replace("Ặ", "A");
            text = text.Replace("ặ", "a");
            text = text.Replace("Ậ", "A");
            text = text.Replace("ậ", "a");
            text = text.Replace("Ẹ", "E");
            text = text.Replace("ẹ", "e");
            text = text.Replace("Ệ", "E");
            text = text.Replace("ệ", "e");
            text = text.Replace("Ị", "I");
            text = text.Replace("ị", "i");
            text = text.Replace("Ọ", "O");
            text = text.Replace("ọ", "o");
            text = text.Replace("Ộ", "O");
            text = text.Replace("ộ", "o");
            text = text.Replace("Ợ", "O");
            text = text.Replace("ợ", "o");
            text = text.Replace("Ụ", "U");
            text = text.Replace("ụ", "u");
            text = text.Replace("Ự", "U");
            text = text.Replace("ự", "u");
            text = text.Replace("Ỵ", "Y");
            text = text.Replace("ỵ", "y");
            text = text.Replace("Đ", "D");
            text = text.Replace("đ", "d");
            return text;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            string strPath;
            if (Session["siteguid"] != null)
            {
                if (!Page.IsPostBack)
                {
                    // check if the query string variable "strPath" has a value
                    // if it does, we are navigating a folder that is under the root folder
                    // if it does not, we start at the root folder by default
                    if (Request.QueryString["strPath"] != null)
                    {
                        strPath = Request.QueryString["strPath"];
                    }
                    else
                    {

                        strPath = strDefaultPath + "/" + Session["siteguid"].ToString();
                    }

                    // delete file

                    if (Request.QueryString["action"] == "delete" && Request.QueryString["fileid"] != "")
                    {
                        DeleteFile(Request.QueryString["fileid"], strDriveLetter + strPath);

                    }

                    CheckSiteFolder(strPath);
                    DisplayDirContents(strPath);

                }
            }
            else
            {
                txtFolder.Visible = false;
                txtFile.Visible = false;
                btnCreateFolder.Visible = false;
                btnUpload.Visible = false;
                output.Text = "<style>#toolbars{display:none;}</style><span style=\"color:red;\">Bạn chưa đăng nhập hoặc phiên đăng nhập đã hết hiệu lực!</span>";
            }

        }

        private void CheckSiteFolder(string strPath)
        {
            if (!Directory.Exists(strDriveLetter + strPath))
            {
                Directory.CreateDirectory(strDriveLetter + strDefaultPath + "/" + Session["siteguid"].ToString());
            }
        }


        private void DisplayDirContents(string strPath)
        {

            // define some arrays 
            DirectoryInfo[] aryDirectories;
            FileInfo[] aryFiles;

            // variable to store the complete file system path to the folder
            string strFSPath = strDriveLetter + strPath;

            // some string manipulation to get the name of the current script
            string strCurrentScript = Request.ServerVariables["URL"];
            string[] arrURL = strCurrentScript.Split('/');
            strCurrentScript = arrURL[arrURL.Length - 1];

            // logic to display the link to navigate "up one level"
            // display the link if not already at root level
            output.Text += "<div id=\"myList\" class=\"fileList\">";
            if (strPath != "" && strPath != strDefaultPath + "/" + Session["siteguid"].ToString())
            {
                output.Text += "<div class=\"item\"><div class=\"image\"><a href=\"" + strCurrentScript + "?strPath=" + strPath.Substring(0, strPath.LastIndexOf("/")) + "\"><img src=\"/Content/images/up.png\"></a></div><div class=\"text\"><a href=\"" + strCurrentScript + "?strPath=" + strPath.Substring(0, strPath.LastIndexOf("/")) + "\"><i>Up One Folder</i></a></div></div>";
            }

            // instantiate local instance of DirectoryInfo object
            DirectoryInfo objCurrentDirectory = new DirectoryInfo(strFSPath);

            // get the directories present in the current folder
            // as an array of DirectoryInfo objects
            aryDirectories = objCurrentDirectory.GetDirectories();

            // check if the current folder has any sub-folders
            if (aryDirectories.Length != 0)
            {
                // if it does, then iterate and 
                // display the information about each folder		
                foreach (DirectoryInfo objDirectory in aryDirectories)
                {
                    output.Text += "<div class=\"item\"><div class=\"image\"><a href=\"" + strCurrentScript + "?strPath=" + strPath + "/" + objDirectory.Name + "\"><img width=\"90px\" src=\"/Content/images/folder.gif\" alt=\"\"/></a></div><div class=\"text\"><a href=\"" + strCurrentScript + "?strPath=" + strPath + "/" + objDirectory.Name + "\">" + objDirectory.Name + "</a></div></div>";
                }
            }

            // get the files present in the current folder
            // as an array of FileInfo objects
            aryFiles = objCurrentDirectory.GetFiles();
            //IComparer comp = new FileComparer(FileComparer.CompareBy.LastWriteTime);
            //Array.Sort(aryFiles, comp);
            var sort = from fn in aryFiles
                       orderby fn.LastWriteTime descending
                       select fn;

            // check if the current folder has any files
            //if (aryFiles.Length != 0)
            if (sort != null)
            {
                // if it does, then iterate and 
                // display the information about each file
                foreach (FileInfo objFile in sort)
                {
                    output.Text += "<div  class=\"item\"><div id=" + objFile.Name + " class=\"image\"><a a href=\"javascript:void(0);\" onClick=\"post_value('" + strPath + "/" + objFile.Name + "');\" ><img src=\"http://atfmaster.com/Editor/aspnet/dlf/" + System.IO.Path.GetExtension(objFile.Name) + ".gif\" alt=\"\"/></a></div><div class=\"text\"><a onclick=\"post_value('" + strPath + objFile.Name + "');\">" + objFile.Name + "</a></div></div>";
                }
            }
            output.Text += "</div>";
        }


        protected void DeleteFile(string strFile, string strPath)
        {
            try
            {
                FileInfo objFile = new FileInfo(strPath + "/" + strFile);
                if (objFile.Exists)
                {
                    System.IO.File.Delete(strPath + "/" + strFile);
                    Response.Redirect("Documents.aspx");
                }
                else
                {
                    throw new FileNotFoundException();
                }
            }
            catch (FileNotFoundException ex)
            {
                output.Text = ex.Message;
            }
        }

        protected void btnCreateFolder_Click(object sender, EventArgs e)
        {

            string sPath = "";
            string url = "";
            if (Request.QueryString["strPath"] != null)
            {
                sPath = Request.QueryString["strPath"];
                url = Request.QueryString["strPath"];
            }
            else
            {
                sPath = "Uploads/" + Session["siteguid"].ToString();
                url = "";
            }
            string sFolderName = txtFolder.Text.Trim();

            char[] SpecialChars = "\\/:?<>.-',~|&()=#@*+;`".ToCharArray();

            int indexOf = sFolderName.IndexOfAny(SpecialChars);

            // check exist folder
            if (!Directory.Exists(strDriveLetter + sPath + "/" + Convert(sFolderName).ToLower()))
            {
                // check valid folder name
                if (indexOf == -1)
                {
                    Directory.CreateDirectory(strDriveLetter + sPath + "/" + Convert(sFolderName).ToLower());
                    if (url != "")
                    {
                        Response.Redirect("Documents.aspx?strPath=" + Request.QueryString["strPath"]);
                    }
                    else
                    {
                        Response.Redirect("Documents.aspx");
                    }
                }
                else
                {
                    txtFolder.Focus();
                    Alert.Show("Tên folder không hợp lệ!");
                }
            }
            else
            {
                txtFolder.Focus();
                Alert.Show("Tên folder đã tồn tại!");
            }

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            // remove unicode


            Regex re = new Regex("[;\\\\/:*?\"<>|&']");
            //string outputString = re.Replace(inputString, " ");

            string sPath = "";
            string url = "";
            if (Request.QueryString["strPath"] != null)
            {
                sPath = Request.QueryString["strPath"];
                url = Request.QueryString["strPath"];
            }
            else
            {
                sPath = "documents/" + Session["siteguid"].ToString();
                url = "";
            }

            if (txtFile.HasFile == true && txtFile.PostedFile != null)
            {
                // file size
                int iFileSize = 9437184;
                // file Extension
                string fileExt = System.IO.Path.GetExtension(txtFile.FileName);


                if (chkValidExtension(fileExt) == true)
                {


                    // Check FileSize
                    if (txtFile.PostedFile.ContentLength <= iFileSize)
                    {
                        if (!System.IO.File.Exists(strDriveLetter + sPath + "/" + re.Replace(Convert(txtFile.FileName.ToLower()), "")))
                        {
                            txtFile.PostedFile.SaveAs(strDriveLetter + sPath + "/" + re.Replace(Convert(txtFile.FileName.ToLower()), ""));
                            if (url != "")
                            {
                                Response.Redirect("Documents.aspx?strPath=" + Request.QueryString["strPath"]);
                            }
                            else
                            {
                                Response.Redirect("Documents.aspx");
                            }
                        }
                        else
                        {
                            // rename file
                            string snewFile = DateTime.Now.ToString("yyyyMMddHHmmss") + re.Replace(Convert(txtFile.FileName.ToLower()), "");
                            txtFile.PostedFile.SaveAs(strDriveLetter + sPath + "/" + snewFile);
                            if (url != "")
                            {
                                Response.Redirect("Documents.aspx?strPath=" + Request.QueryString["strPath"]);
                            }
                            else
                            {
                                Response.Redirect("Documents.aspx");
                            }
                        }
                    }
                    else
                    {
                        Alert.Show("Dung lượng file quá lớn!");
                    }

                }
                else
                {
                    Alert.Show("Tên file không hợp lệ!");
                }

            }
        }

        public static FileSystemRights GetDirectoryPermissions(string user, string domainName, string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                return (0);
            }

            string identityReference = ((domainName + @"\" + user) as string).ToLower();
            DirectorySecurity dirSecurity = Directory.GetAccessControl(folderPath, AccessControlSections.Access);
            foreach (FileSystemAccessRule fsRule in dirSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
            {
                if (fsRule.IdentityReference.Value.ToLower() == identityReference)
                {
                    return (fsRule.FileSystemRights);
                }
            }
            return (0);
        }

        public bool chkValidExtension(string ext)
        {

            string[] PosterAllowedExtensions = new string[] { ".zip", ".rar", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pdf" };
            for (int i = 0; i < PosterAllowedExtensions.Length; i++)
            {
                if (ext == PosterAllowedExtensions[i])
                    return true;
            }

            return false;

        }

        public static class Alert
        {
            // Shows a client-side JavaScript alert in the browser.
            // <param name="message">The message to appear in the alert.</param>
            public static void Show(string message)
            {
                // Cleans the message to allow single quotation marks
                string cleanMessage = message.Replace("'", "\\'");
                string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

                // Gets the executing web page
                Page page = HttpContext.Current.CurrentHandler as Page;

                // Checks if the handler is a Page and that the script isn't allready on the Page
                if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
                {
                    page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
                }
            }
        }
    }
}